const router = require('express').Router()
const { v4: uuidv4 } = require('uuid');
const path = require("path")
const fs = require("fs")
//导入 multer
const multer = require("multer")

const qiniu = require("qiniu")

//配置三个空间 => 生成token
var accessKey = 'n5SIZ2g682y929cbdgPHmrwhX9j_ShsCu56hGZ0U';
var secretKey = 'iP-GXjDBSsJkBZlxJm57Pbrkd1PE_Bb4ITCTlGyD';
var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
//七牛云的仓库
var options = {
    scope: "wenzhongyu",
};
var putPolicy = new qiniu.rs.PutPolicy(options);
//根据三个信息生成七牛云的token
var uploadToken = putPolicy.uploadToken(mac);

// 图片存储的机房地址
var config = new qiniu.conf.Config();
// 空间对应的机房
config.zone = qiniu.zone.Zone_z2;


//图片上传 => 配置存储(配置仓库)
const storage = multer.diskStorage({
    //存储路径
    destination(req, file, cb) {
        cb(null, "public")
    },
    //存储名称
    filename(req, file, cb) {
        cb(null, uuidv4() + path.extname(file.originalname))
    }
})

//实现存储
const storageInfo = multer({ storage })

//三级路由 => 
router.post("/file", storageInfo.single('wy'), (req, res) => {

    //图片上传
    var localFile = req.file.path;//本地图片路径
    var formUploader = new qiniu.form_up.FormUploader(config);
    var putExtra = new qiniu.form_up.PutExtra();

    // 文件上传
    formUploader.putFile(uploadToken, null, localFile, putExtra, function (respErr,respBody, respInfo) {
        if (respErr) {
            throw respErr;
        }
        //七牛云服务器给你的服务器响应成功,那么就把public里面的图片给删除
        if (respInfo.statusCode == 200) {
            fs.unlink(localFile,(err)=>{
                if(err) console.log("删除图片失败");
                console.log("删除图片成功");
            })
            res.send({code:200,msg:`http://s08vr7vdh.hn-bkt.clouddn.com/${respBody.hash}`})
        } else {
            console.log(respBody);
        }
    });
})



module.exports = router